package br.ufc.great.dtx.tm.deadlockdetector;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import br.ufc.great.dtx.server.DTXOutput;
import br.ufc.great.dtx.server.config.DTXSite;

/**
 * 
 * @author Leonardo Oliveira Moreira
 *
 * Processo inicializado periodicamente para verificar a ocorrência de deadlock distribuído
 */
public class DeadLockDaemonThread extends Thread {

	private DTXOutput output;
	private DeadLockDaemon daemon;
	private WFGMessage message;
	private Socket socket;
	private DTXSite site;
	
	public DeadLockDaemonThread(DTXOutput output, DeadLockDaemon daemon, DTXSite site, WFGMessage message) throws UnknownHostException, IOException {
		this.output = output;
		this.daemon = daemon;
		this.site = site;
		this.message = message;
		socket = new Socket(site.getHost(), site.getPort());
		setPriority(MIN_PRIORITY);
	}
	
	public void run() {
		try {
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			out.writeObject(message);
			out.flush();
			daemon.addRequest();
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
			WFGMessage message = (WFGMessage) in.readObject();
			//output.print(getClass().getSimpleName(), "Response arrived", DTXOutput.TEST);
			in.close();
			socket.close();
			daemon.addGraph(message.getGraph());
		}
		catch (IOException e) {
			output.print(getClass().getSimpleName(), e.getMessage(), DTXOutput.ERROR);
			daemon.addResponse();
		}
		catch (ClassNotFoundException e) {
			output.print(getClass().getSimpleName(), e.getMessage(), DTXOutput.ERROR);
			daemon.addResponse();
		}
		
	}
	
}
